/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.plc4x.java.cbus.readwrite;

import static org.apache.plc4x.java.spi.codegen.fields.FieldReaderFactory.*;
import static org.apache.plc4x.java.spi.codegen.fields.FieldWriterFactory.*;
import static org.apache.plc4x.java.spi.codegen.io.DataReaderFactory.*;
import static org.apache.plc4x.java.spi.codegen.io.DataWriterFactory.*;
import static org.apache.plc4x.java.spi.generation.StaticHelper.*;

import java.time.*;
import java.util.*;
import org.apache.plc4x.java.api.exceptions.*;
import org.apache.plc4x.java.api.value.*;
import org.apache.plc4x.java.spi.codegen.*;
import org.apache.plc4x.java.spi.codegen.fields.*;
import org.apache.plc4x.java.spi.codegen.io.*;
import org.apache.plc4x.java.spi.generation.*;

// Code generated by code-generation. DO NOT EDIT.

public abstract class Request implements Message {

  // Abstract accessors for discriminator values.

  // Properties.
  protected final RequestType peekedByte;
  protected final RequestType startingCR;
  protected final RequestType resetMode;
  protected final RequestType secondPeek;
  protected final RequestTermination termination;

  public Request(
      RequestType peekedByte,
      RequestType startingCR,
      RequestType resetMode,
      RequestType secondPeek,
      RequestTermination termination) {
    super();
    this.peekedByte = peekedByte;
    this.startingCR = startingCR;
    this.resetMode = resetMode;
    this.secondPeek = secondPeek;
    this.termination = termination;
  }

  public RequestType getPeekedByte() {
    return peekedByte;
  }

  public RequestType getStartingCR() {
    return startingCR;
  }

  public RequestType getResetMode() {
    return resetMode;
  }

  public RequestType getSecondPeek() {
    return secondPeek;
  }

  public RequestTermination getTermination() {
    return termination;
  }

  public RequestType getActualPeek() {
    return (RequestType)
        (((((((getStartingCR()) == (null)) && ((getResetMode()) == (null))))
                || (((((getStartingCR()) == (null)) && ((getResetMode()) != (null)))
                    && ((getSecondPeek()) == (RequestType.EMPTY)))))
            ? getPeekedByte()
            : getSecondPeek()));
  }

  protected abstract void serializeRequestChild(WriteBuffer writeBuffer)
      throws SerializationException;

  public void serialize(WriteBuffer writeBuffer) throws SerializationException {
    PositionAware positionAware = writeBuffer;
    boolean _lastItem = ThreadLocalHelper.lastItemThreadLocal.get();
    writeBuffer.pushContext("Request");

    // Optional Field (startingCR) (Can be skipped, if the value is null)
    writeOptionalEnumField(
        "startingCR",
        "RequestType",
        startingCR,
        writeEnum(RequestType::getValue, RequestType::name, writeUnsignedShort(writeBuffer, 8)),
        (getPeekedByte()) == (RequestType.EMPTY));

    // Optional Field (resetMode) (Can be skipped, if the value is null)
    writeOptionalEnumField(
        "resetMode",
        "RequestType",
        resetMode,
        writeEnum(RequestType::getValue, RequestType::name, writeUnsignedShort(writeBuffer, 8)),
        (getPeekedByte()) == (RequestType.RESET));

    // Virtual field (doesn't serialize anything, just makes the value available)
    RequestType actualPeek = getActualPeek();
    writeBuffer.writeVirtual("actualPeek", actualPeek);

    // Switch field (Serialize the sub-type)
    serializeRequestChild(writeBuffer);

    // Simple Field (termination)
    writeSimpleField("termination", termination, writeComplex(writeBuffer));

    writeBuffer.popContext("Request");
  }

  @Override
  public int getLengthInBytes() {
    return (int) Math.ceil((float) getLengthInBits() / 8.0);
  }

  @Override
  public int getLengthInBits() {
    int lengthInBits = 0;
    Request _value = this;
    boolean _lastItem = ThreadLocalHelper.lastItemThreadLocal.get();

    // Optional Field (startingCR)
    if (startingCR != null) {
      lengthInBits += 8;
    }

    // Optional Field (resetMode)
    if (resetMode != null) {
      lengthInBits += 8;
    }

    // A virtual field doesn't have any in- or output.

    // Length of sub-type elements will be added by sub-type...

    // Simple field (termination)
    lengthInBits += termination.getLengthInBits();

    return lengthInBits;
  }

  public static Request staticParse(ReadBuffer readBuffer, CBusOptions cBusOptions)
      throws ParseException {
    readBuffer.pullContext("Request");
    PositionAware positionAware = readBuffer;
    boolean _lastItem = ThreadLocalHelper.lastItemThreadLocal.get();

    RequestType peekedByte =
        readPeekField(
            "peekedByte", readEnum(RequestType::enumForValue, readUnsignedShort(readBuffer, 8)));

    RequestType startingCR =
        readOptionalField(
            "startingCR",
            readEnum(RequestType::enumForValue, readUnsignedShort(readBuffer, 8)),
            (peekedByte) == (RequestType.EMPTY));

    RequestType resetMode =
        readOptionalField(
            "resetMode",
            readEnum(RequestType::enumForValue, readUnsignedShort(readBuffer, 8)),
            (peekedByte) == (RequestType.RESET));

    RequestType secondPeek =
        readPeekField(
            "secondPeek", readEnum(RequestType::enumForValue, readUnsignedShort(readBuffer, 8)));
    RequestType actualPeek =
        readVirtualField(
            "actualPeek",
            RequestType.class,
            ((((((startingCR) == (null)) && ((resetMode) == (null))))
                    || (((((startingCR) == (null)) && ((resetMode) != (null)))
                        && ((secondPeek) == (RequestType.EMPTY)))))
                ? peekedByte
                : secondPeek));

    // Switch Field (Depending on the discriminator values, passes the instantiation to a sub-type)
    RequestBuilder builder = null;
    if (EvaluationHelper.equals(actualPeek, RequestType.SMART_CONNECT_SHORTCUT)) {
      builder = RequestSmartConnectShortcut.staticParseRequestBuilder(readBuffer, cBusOptions);
    } else if (EvaluationHelper.equals(actualPeek, RequestType.RESET)) {
      builder = RequestReset.staticParseRequestBuilder(readBuffer, cBusOptions);
    } else if (EvaluationHelper.equals(actualPeek, RequestType.DIRECT_COMMAND)) {
      builder = RequestDirectCommandAccess.staticParseRequestBuilder(readBuffer, cBusOptions);
    } else if (EvaluationHelper.equals(actualPeek, RequestType.REQUEST_COMMAND)) {
      builder = RequestCommand.staticParseRequestBuilder(readBuffer, cBusOptions);
    } else if (EvaluationHelper.equals(actualPeek, RequestType.NULL)) {
      builder = RequestNull.staticParseRequestBuilder(readBuffer, cBusOptions);
    } else if (EvaluationHelper.equals(actualPeek, RequestType.EMPTY)) {
      builder = RequestEmpty.staticParseRequestBuilder(readBuffer, cBusOptions);
    } else if (true) {
      builder = RequestObsolete.staticParseRequestBuilder(readBuffer, cBusOptions);
    }
    if (builder == null) {
      throw new ParseException(
          "Unsupported case for discriminated type"
              + " parameters ["
              + "actualPeek="
              + actualPeek
              + "]");
    }

    RequestTermination termination =
        readSimpleField(
            "termination",
            readComplex(() -> RequestTermination.staticParse(readBuffer), readBuffer));

    readBuffer.closeContext("Request");
    // Create the instance
    Request _request = builder.build(peekedByte, startingCR, resetMode, secondPeek, termination);
    return _request;
  }

  public interface RequestBuilder {
    Request build(
        RequestType peekedByte,
        RequestType startingCR,
        RequestType resetMode,
        RequestType secondPeek,
        RequestTermination termination);
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (!(o instanceof Request)) {
      return false;
    }
    Request that = (Request) o;
    return (getPeekedByte() == that.getPeekedByte())
        && (getStartingCR() == that.getStartingCR())
        && (getResetMode() == that.getResetMode())
        && (getSecondPeek() == that.getSecondPeek())
        && (getTermination() == that.getTermination())
        && true;
  }

  @Override
  public int hashCode() {
    return Objects.hash(
        getPeekedByte(), getStartingCR(), getResetMode(), getSecondPeek(), getTermination());
  }

  @Override
  public String toString() {
    WriteBufferBoxBased writeBufferBoxBased = new WriteBufferBoxBased(true, true);
    try {
      writeBufferBoxBased.writeSerializable(this);
    } catch (SerializationException e) {
      throw new RuntimeException(e);
    }
    return "\n" + writeBufferBoxBased.getBox().toString() + "\n";
  }
}
